package net.sourceforge.zbar.android.CameraTest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {
	 

	
	public GCMIntentService() {
	super(CameraTestActivity.GCM_SENDER_ID);
	}
	 
	private static final String TAG = "===GCMIntentService===";
	 
	@Override
	protected void onRegistered(Context arg0, String registrationId) {
		Log.i("YOLO", "FS dump");
		getFS();
//		for(String s : getFS())
//			Log.i("YOLO", s);
		
	Log.i(TAG, "Device registered: regId = " + registrationId);
	if(registrationId != null)
		CommonUtilities.setDeviceRID(registrationId);
	}
	
	@Override
	protected void onUnregistered(Context arg0, String arg1) {
	Log.i(TAG, "unregistered = "+arg1);
	}
	 
	@Override
	protected void onMessage(Context arg0, Intent arg1) {
		Log.i(TAG, "new message= "+arg1.getStringExtra("message"));
		
		if(arg1.getStringExtra("message").equals("ACKNOWLEDGED")){
			String req = "http://android-wfs.appspot.com/pair?action=2&device_rid="+CommonUtilities.getDeviceRID()+"&token="+CommonUtilities.getToken();
			HttpClient httpclient = new DefaultHttpClient();
			try {
				httpclient.execute(new HttpGet(req));
			} catch (Exception e) {
				Log.e("Shit happened","Cannot make request");
			}
		}
		

	}
	 
	@Override
	protected void onError(Context arg0, String errorId) {
	Log.i(TAG, "Received error: " + errorId);
	}
	 
	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
	return super.onRecoverableError(context, errorId);
	}
	
    private List<String> items = new ArrayList<String>();
    
    private List<String> getFS(){
    	items = new ArrayList<String>();
    	getFiles(new File("/sdcard").listFiles());
    	return items;
    }
    
	 private void getFiles(File[] files){
		 if(files != null) {
	        for(File file : files) {
	        	Log.i("YOLO", file.getPath());
	        	if(!items.contains(file.getPath()))
	        		items.add(file.getPath());
	        	else
	        		break;
	            if(file.isAbsolute())
	            	getFiles(file.listFiles());
	        }
		 }
	 }

}
